<?php

namespace app\admin\controller\staff;

use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use fast\Tree;
use think\Config;
use think\Db;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;
use think\Model;
use think\response\Json;
use think\Session;

/**
 * 员工管理
 *
 * @icon fa fa-circle-o
 */
class Staff extends Backend
{

    /**
     * Staff模型对象
     * @var \app\admin\model\staff\Staff
     */
    protected $model = null;
    protected $_admin = '';
    protected $shop_id = '';
    protected $staff_salary_model = null;
    protected $rank_model = null;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\staff\Staff;

        $this->_admin = Session::get('adminshop');
        $this->shop_id = Session::get('shop');
        $this->staff_salary_model = new \app\admin\model\staff\Salary;
        $this->rank_model = new \app\admin\model\wanlshop\staff\Rank;
        $this->view->assign("maritalstatusList", $this->model->getMaritalstatusList());
        $this->view->assign("employeestatusList", $this->model->getemployeestatusList());
        $this->view->assign("minguaranteeList", $this->model->getminguaranteeList());

        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("politicaloutlookList", $this->model->getPoliticaloutlookList());
        $this->view->assign("educationList", $this->model->getEducationList());
        $this->view->assign("tagList", $this->model->getTagList());
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("adminshop", $this->_admin);
        $this->view->assign("currshop", $this->shop_id);

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        
        if ($this->shop_id == $this->_admin && $this->_admin == 1) {
            $condition = [];
        }else{
            $condition = ['shop_id'=>$this->shop_id];
        }
        
        
        $list = $this->model
            ->with(['rank','jobgrade','department','staffrank'])
            ->where($where)
            ->where($condition)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add(){
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if(empty($params['rank_second'])){
                $this->error('请选择职级');
            }
            if(empty($params['job_second'])){
                $this->error('请选择职位');
            }
            $params['rank'] = $params['rank_second'];
            $params['jobgrade'] = $params['job_second'];
            $result = $this->model->allowField(true)->save($params);

            $params['shop_id'] = 1;
            Db::name('staff_social_security')->insert(['staff_id'=>$this->model->id,'shop_id'=>$params['shop_id']]);
            Db::name('staff_housing_provident_fund')->insert(['staff_id'=>$this->model->id,'shop_id'=>$params['shop_id']]);
            Db::name('staff_salary_card')->insert(['staff_id'=>$this->model->id,'shop_id'=>$params['shop_id']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function qadd(){
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if(empty($params['rank_second'])){
                $this->error('请选择职级');
            }
            if(empty($params['job_second'])){
                $this->error('请选择职位');
            }
            $params['rank'] = $params['rank_second'];
            $params['jobgrade'] = $params['job_second'];
            if ($this->shop_id != 1) {
                $params['shop_id'] = $this->shop_id;
            }

            $result = $this->model->allowField(true)->save($params);
            Db::name('staff_social_security')->insert(['staff_id'=>$this->model->id,'shop_id'=>$params['shop_id']]);
            Db::name('staff_housing_provident_fund')->insert(['staff_id'=>$this->model->id,'shop_id'=>$params['shop_id']]);
            Db::name('staff_salary_card')->insert(['staff_id'=>$this->model->id,'shop_id'=>$params['shop_id']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 查看
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row = $this->model->alias('s')
            ->field('s.*,s.name as name,so.name as soname,so.account as account,so.startingpaymentmonth as startingpaymentmonth,so.level as level,so.base as base,so.insuredplace as insuredplace,so.id as soid,h.id as hid,c.id as cid,so.status as sostatus,wan.id,wan.shopname,h.account as accumulation_account,h.name as hname,h.startingpaymentmonth as accumulation_startingpaymentmonth,h.base as accumulation_base,h.placepayment as accumulation_placepayment,c.id as cid,c.shop_id as cshop_id,c.bankcard,c.openingbank as openingbank,c.name as bankName,s.id as staff_id,s.rank_id as rank_id,sr.name as staff_rank_name')
            ->join('staff_social_security so','s.id = so.staff_id','left')
            ->join('staff_housing_provident_fund h' ,'s.id = h.staff_id','left')
            ->join('wanlshop_shop wan','s.shop_id = wan.id','left')
            ->join('wanlshop_staff_rank sr','sr.id = s.rank_id','left')
            ->join('staff_salary_card c','s.id = c.staff_id','left')
            ->where(['s.id'=>$ids])
            ->find();

        switch ($row['politicaloutlook']){
            case '0':
                //政治面貌:0=群众,1=党员,2=其他党派
                $row['politicaloutlook'] = '群众';
                break;
                case '1':
                //政治面貌:0=群众,1=党员,2=其他党派
                $row['politicaloutlook'] = '党员';
                break;
                case '2':
                    $row['politicaloutlook'] = '其他党派';
                    break;
        }
        switch ($row['sex']){
            case '1':
                $row['sex'] = '男';
                break;
            case '2':
                $row['sex'] = '女';
                break;
        }
        switch ($row['maritalstatus']){
            case '0':
                //政治面貌:0=群众,1=党员,2=其他党派
                $row['maritalstatus'] = '未婚';
                break;
            case '1':
                //政治面貌:0=群众,1=党员,2=其他党派
                $row['maritalstatus'] = '已婚';
                break;
        }
 //学历:0=硕士及以上,1=本科,2=专科,3=中专/高中,4=高中以下
        switch ($row['education']){
            case '0':
                //政治面貌:0=群众,1=党员,2=其他党派
                $row['education'] = '硕士及以上';
                break;
            case '1':
                //政治面貌:0=群众,1=党员,2=其他党派
                $row['education'] = '本科';
                break;
            case '2':
                $row['education'] = '专科';
                break;
            case '3':
                $row['education'] = '中专/高中';
                break;
            case '4':
                $row['education'] = '高中以下';
                break;
        }

        $row['confirmationtime'] = empty($row['confirmationtime'])?'':date('Y-m-d H:i:s',$row['confirmationtime']);
        $row['signingtime'] = empty($row['signingtime'])?'':date('Y-m-d H:i:s',$row['signingtime']);
        $row['expirationtime'] = empty($row['expirationtime'])?'':date('Y-m-d H:i:s',$row['expirationtime']);
        $row['employmenttime'] = empty($row['employmenttime'])?'':date('Y-m-d H:i:s',$row['employmenttime']);

        
        $rank_name = Db::name('staff_rank')->where(['id'=>$row['rank']])->find();
        $row['rank_first'] = Db::name('staff_rank')->where(['id'=>$rank_name['pid']])->find();
        $row['rank_second'] = Db::name('staff_rank')->where(['id'=>$row['rank']])->find();
        $job_first = Db::name('staff_job')->where(['id'=>$row['jobgrade']])->find();
        $row['job_first'] = Db::name('staff_job')->where(['id'=>$job_first['pid']])->find();
        $row['job_second'] = Db::name('staff_job')->where(['id'=>$row['jobgrade']])->find();

        $job = Db::name('staff_job')->where(['id'=>$row['jobgrade']])->value('name');
        $rank = Db::name('staff_rank')->where(['id'=>$row['rank']])->value('name');
        $shopname= Db::name('wanlshop_shop')->where(['id'=>$row['shop_id']])->value('shopname');

        $this->view->assign('shopname', $shopname);
        $this->view->assign('row', $row);
        $this->view->assign('job', $job);
        $this->view->assign('rank', $rank);
        return $this->view->fetch();

    }
    /*
     *  工资表单
     */
    public function wages($ids = null){
//设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $conditions = ['staff_id'=>$ids];
        $list = $this->staff_salary_model
            ->where($conditions)
            ->order('id','desc')
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $rank_name = Db::name('staff_rank')->where(['id'=>$row['rank']])->find();
            $row['rank_first'] = Db::name('staff_rank')->where(['id'=>$rank_name['pid']])->find();
            $row['rank_second'] = Db::name('staff_rank')->where(['id'=>$row['rank']])->find();
            $job_first = Db::name('staff_job')->where(['id'=>$row['jobgrade']])->find();
            $row['job_first'] = Db::name('staff_job')->where(['id'=>$job_first['pid']])->find();
            $row['job_second'] = Db::name('staff_job')->where(['id'=>$row['jobgrade']])->find();
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if(empty($params['rank_second'])){
                $this->error('请选择职级');
            }
            if(empty($params['job_second'])){
                $this->error('请选择职位');
            }
            $params['rank'] = $params['rank_second'];
            $params['jobgrade'] = $params['job_second'];
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");

        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => $item[$primarykey] ?? '',
                        $field      => $item[$field] ?? '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = max(0, $this->request->get("offset/d", 0));
        $limit = max(0, $this->request->get("limit/d", 0));
        $limit = $limit ?: 999999;

        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = max(0, $this->request->get("page/d", 1));
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        if (isset($filter['department.shopname'])){
            $filter['department'] = $filter['department.shopname'];
            unset($filter['department.shopname']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = $op[$k] ?? '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper($op[$k] ?? $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
                        && !empty($this->model) && $this->relationSearch) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }
    public function saveportraitimage(){
        $id = $this->request->post("id");
        $portraitimage = $this->request->post("portraitimage");
        DB::name("staff")->where("id",$id)->update(["portraitimage"=>$portraitimage]);
        $this->success();
    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import(){
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        // 根据文件类型选择解析器
        if ($ext === 'csv') {
            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        // 加载文件
        $objPHPExcel = $reader->load($filePath);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        // 读取表头
        $headers = [];
        $headers = ['id','type','name','mobile','datebirth','staffcode','employmenttime','department','jobgrade','rank'];

        // 读取数据行
        $data = [];
        for ($row = 2; $row <= $highestRow; $row++) {
            $rowData = [];
            for ($col = 0; $col < count($headers); $col++) {
                $cell = $sheet->getCellByColumnAndRow($col, $row);
                $rowData[$headers[$col]] = $cell->getValue();
            }
            unset($rowData['id']);
            $data[] = $rowData;
        }

        $res = true;
        $type_list = ['正式工','退休返聘','实习生','派遣工'];
        if (count($data) > 0) {
            foreach ($data as $key => &$row) {
                $staff_staffcode = $this->model->where(['staffcode'=>$row['staffcode']])->find();
                if (!empty($staff_staffcode)) {
                    unset($data[$key]);
                    continue;
                }

                if (isset($row['datebirth'])) {
                    $row['datebirth'] = date('Y-m-d', (trim($row['datebirth']) - 25569) * 24 * 3600);
                }

                if (isset($row['employmenttime'])) {
                    $row['employmenttime'] = strtotime(date('Y-m-d', (trim($row['employmenttime']) - 25569) * 24 * 3600));
                }
                $row['createtime'] = time();
                $row['shop_id'] = $this->shop_id;
                $type = array_search($row['type'],$type_list);
                $row['type'] = !empty($type)?$type:0;
                $rank_info = Db::name('staff_rank')->where(['name'=>$row['rank']])->find();
                $row['rank'] = !empty($rank_info)?$rank_info['id']:'';
                $jobgrade_info = Db::name('staff_job')->where(['name'=>$row['jobgrade']])->find();
                $row['jobgrade'] = !empty($jobgrade_info)?$jobgrade_info['id']:'';
                $shop_info = Db::name('wanlshop_shop')->where(['shopname'=>$row['department']])->find();
                $row['department'] = !empty($shop_info)?$shop_info['id']:'0';
            }
        }

        if (count($data) > 0) {
            // 处理数据并插入数据库
            $res = $this->model->insertAll($data);
            // print_r($this->model->getLastSql());die;
        }

        if (false === $res) {
            $this->error(__('No rows were inserted'));
        }

        $this->success(__('导入成功'), null, ['count' => count($data)]);
    }

    //员工调动
    public function transfer($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $rank_name = Db::name('staff_rank')->where(['id'=>$row['rank']])->find();
            $row['rank_first'] = Db::name('staff_rank')->where(['id'=>$rank_name['pid']])->find();
            $row['rank_second'] = Db::name('staff_rank')->where(['id'=>$row['rank']])->find();
            $job_first = Db::name('staff_job')->where(['id'=>$row['jobgrade']])->find();
            $row['job_first'] = Db::name('staff_job')->where(['id'=>$job_first['pid']])->find();
            $row['job_second'] = Db::name('staff_job')->where(['id'=>$row['jobgrade']])->find();
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $result = false;
        Db::startTrans();
        try {
            if(empty($params['rank_second'])){
                $this->error('请选择职级');
            }
            if(empty($params['job_second'])){
                $this->error('请选择职位');
            }
            $row->rank = $params['rank_second'];
            $row->jobgrade = $params['job_second'];

            $result = $row->save();
            if (false === $result) {
                Db::rollback();
                $this->error(__('No rows were updated'));
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //离职
    public function resign($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $result = false;
        Db::startTrans();
        try {
            $row->status = '0';
            $result = $row->save();
            if (false === $result) {
                Db::rollback();
                $this->error(__('No rows were updated'));
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        $this->success();
    }
}
